﻿using System;
using System.Collections.Generic;
using System.IO;
using com.byt.webcore;
using System.Text;
using System.Web;
using com.byt.webcore.utils;

namespace suce.upload
{
    /// <summary>
    /// Summary description for Download
    /// </summary>
    public class Download : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            UploadHelper.pathFiles = AppConfig.getPath(null, "upload");

            string pathFiles = UploadHelper.pathFiles;

            string folder = context.Request.Params["folder"];

            if (folder.IndexOf("%2F")>0)
            {
                folder = folder.Replace("%2F", "/");
            }

            string file = Utils.DecodeURIComponent(context.Request.Params["file"]);

            String path = Path.Combine(Path.Combine(pathFiles, folder), file);

            if (File.Exists(path))
            {
                context.Response.ContentType = MimeType.Get(Path.GetExtension(file));

                string ext = Path.GetExtension(file);
                if (string.IsNullOrEmpty(ext))
                    ext = "";
                ext = ext.ToLower() + "/";
                if (".pdf/.txt/.jpg/.gif/.tiff/.png/.jpeg/.doc/.docx/".IndexOf(ext) < 0)
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file + "\"");

                context.Response.WriteFile(path);

                context.Response.Flush();
            }
            else
            {
                context.Response.Write("El archivo Adjunto no existe ó existe un problema con el nombre del archivo<br>Comuniquese con el Administrador del sistema.");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}